﻿using AutoMapper;
using MediatR;
using SmartCity.BasicData.Api.Write.Application.Command.Account;
using SmartCity.BasicData.Common;
using SmartCity.BasicData.Domain;
using SmartCity.BasicData.Repo;
using SmartCity.BasicData.Repo.Impl;

namespace SmartCity.BasicData.Api.Write.Application.Handler.Account
{
    /// <summary>
    /// Account - API
    /// </summary>
    public class DelAccountHandler :IRequestHandler<DelAccountCommand, ApiResult<int>>
    {
        private readonly ILogger<DelAccountHandler> logger;
        private readonly IBaseRepository<AccountModel> accRepo;
        private readonly IMapper mapper;

        public DelAccountHandler(ILogger<DelAccountHandler> logger,IBaseRepository<AccountModel> accRepo,IMapper mapper)
        {
            this.logger = logger;
            this.accRepo = accRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 逻辑删除处理方法
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<int>> Handle(DelAccountCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            
            var user = accRepo.GetModelAsync(id: request.Id).Result;
            if (user == null)
            {
                result.Code = Common.Menus.EnumResultCode.Error;
                result.Msg = "发生错误,要删除的账号不存在";
                result.Data = 0;
            }
            else { 
                user.IsDeleted = true;
              int i =  accRepo.UpdateAsync(user).Result;
                if (i > 0)
                {
                    result.Code = Common.Menus.EnumResultCode.Success;
                    result.Msg = "删除成功!";
                    result.Data = i;
                }
                else {
                    result.Code = Common.Menus.EnumResultCode.Fail;
                    result.Msg = "删除失败!";
                    result.Data = i;
                }
            }
             
            return Task.FromResult(result);             
        }
    }
}
